import React, { PureComponent } from 'react';
import memoize from 'memoize-one';
import { Table, Select, Modal, Input, message,InputNumber } from 'antd';
import api from '../../../../../../api/api';
const Option = Select.Option;
const confirm = Modal.confirm;
const familyRelation = [
  {id:"17",name:"一级亲属关系(父母、子女、兄弟姐妹)"},
  {id:"18",name:"二级亲属关系(爷爷奶奶外公外婆)"},
  {id:"19",name:"二级亲属关系(叔叔姑姑舅舅阿姨)"},
  {id:"11",name:"(外)祖父"},
  {id:"12",name:"(外)祖母"},
  {id:"1",name:"父亲"},
  {id:"2",name:"母亲"},
  {id:"3",name:"兄弟"},
  {id:"7",name:"姐妹"},
  {id:"4",name:"儿女"},
  {id:"6",name:"其它近亲属"},
]
const lapseToIdData = [{ id: '1', name: '带病健康生存' },
  { id: '2', name: '全失能' },
  { id: '3', name: '半失能' },
  { id: '4', name: '疾病控制不佳' },
  { id: '5', name: '死亡' }];
const debounce=(fn, wait=1000)=> {
  var timer = null;
  return function () {
      var context = this
      var args = arguments
      if (timer) {
          clearTimeout(timer);
          timer = null;
      }
      timer = setTimeout(function () {
          fn.apply(context, args)
      }, wait)
  }
}
export default class ChoseSlowSickTabless extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      data: [{
        relationValue:'',
        relation:'',
        diseaseId: '',
        age: '',
        lapseToId: '',
      }],
      chronic_diseaseData: {},
      ownSickListData: [],
      loading:false,
    }
  }
  componentDidMount() {
    this.getDiseasesList()
  }
  getDiseasesList = async () => {
    const { family, own } = await api.getDiseases();
    this.setState({
      ownSickListData:family
    }, () => {
      this.initColumns()
    })
  }
  initColumns = async (noAjax) => {
    let ownSickList = this.state.ownSickListData;
    const self = this
    let data = {familyDiseases:this.state.data}
    if (!noAjax) {
      this.setState({loading:true})
      data = this.props.dataMain || this.state.data; // await api.getPatientDiseaseInfo(this.props.patientId);
      this.setState({
        chronic_diseaseData:data
      }, () => {
        this.setState({loading:false})
      })
    }
    // 判断是否有空的
    let sickData = data;
    if (sickData.length < 1 || !sickData.some(item => !item.id)) {
      const newData = {
        relationValue:'',
        relation:'',
        diseaseId: '',
        age: '',
        lapseToId: '',
      }
      sickData.push(newData)
    }
    this.setState({
      data:sickData,
      columns: [{
        title: '与本人关系',
        dataIndex: 'relation',
        key: 'relation',
        render: memoize((text, record, index) => {
          let val = record.relation || undefined;
          const data = this.state.data[index]
          const isRequ = !data.relation && (data.age || data.lapseToId);
          const domValList = familyRelation.filter(item => item.id === val);
          const domVal = domValList.length > 0 ? domValList[0].name : undefined;
          return (<div className="cursor">
            {record.relationTitle ? <div>{ record.relationTitle }</div>: <Select value={val} style={{ width: '80%', minWidth: '200px' }} placeholder="选择关系" onChange={(value) => self.relationChange(value, index)} disabled={record.id}>
              {familyRelation.map((item) => {
                return (
                  <Option value={item.id} key={item.id} title={item.name}>{item.name}</Option>
                )
              })}
            </Select>}
            {isRequ?<span className="requiredStyle">必填项</span>:null}
          </div>)
        }),
      }, {
        title: '关系人疾病',
        dataIndex: 'sick',
        key: 'sick',
        render: memoize((text, record, index) => {
          let val = record.diseaseId || undefined;
          const data = this.state.data[index]
          const isRequ = !data.diseaseId && (data.age || data.lapseToId)
          return (<div className="cursor">
            <Select value={val} style={{width:'220px'}} placeholder="选择疾病" onChange={(value) => self.sickChange(value,index)} disabled={ record.id }>
              {ownSickList.map((item) => {
                return (
                  <Option value={item.id} key={item.id} title={ `${item.name} (${item.icd10})`}>{item.name}({item.icd10})</Option>
                )
              })}
            </Select>
            {isRequ?<span className="requiredStyle">必填项</span>:null}
          </div>)
        }),
      },{
        title: '患病年龄(岁)',
        dataIndex: 'old',
        key: 'old',
        render: (text, record, index) => {
          let ageVal = record.age || undefined
          return (
            <div className="cursor">
              {record.relationTitle ? <div>{ageVal?ageVal:undefined}</div> : <InputNumber size="large" className="width150" style={{ width: '70px' }} min={18} max={120} value={ageVal} onChange={(value) => self.ageChange(value, index)} onBlur={(value) => self.ageChangeSend(value, index)} disabled={record.id} />}
            </div>
          )
        }
      },{
        title: '转归',
        dataIndex: 'lapseToIds',
        key: 'lapseToIds',
        width:70,
        render: memoize((text, record, index) => {
          let val = record.lapseToId || undefined;
          const domValList = lapseToIdData.filter(item => item.id === val);
          const domVal = domValList.length > 0 ? domValList[0].name : undefined;
          return (<div className="cursor">
            {record.relationTitle ? <div>{domVal}</div> : <Select value={val} placeholder="选择转归" style={{ width: 100 }} onChange={(value) => self.lapseToIdChange(value, index)} disabled={record.id}>
              {lapseToIdData.map((item) => {
                return (
                  <Option value={item.id} key={item.id}>{item.name}</Option>
                )
              })}
            </Select>}
          </div>)
        }),
      }, {
        title: '操作',
        key: 'action',
        width:100,
        render: (text, record, index) => (
          <div className="tabledisplayNone">
            <span className="cursor" style={{marginRight:'15px',display:'inline-block'}} onClick={ ()=>this.deleteSlowSick(record,index) }>
              删除
            </span>
            {index === this.state.data.length-1? <span onClick={() => this.editOwnSickFun()} className="saveBtn">添加</span>:null}
          </div>
        ),
      }]
    })
  }
  // 选择慢病
  sickChange = (value, index) => {
    const { data } = this.state;
    let newData = data;
    newData[index].diseaseId = value
    const initD = JSON.parse(JSON.stringify(newData))
    this.setState({
      data:initD
    })
  }
  // ajax修改慢病情况
  editOwnSickFun = async () => {
    const { patientId } = this.props;
    let { data, chronic_diseaseData } = this.state;
    let updateDiseaseInfo = chronic_diseaseData;
    const isRequest = data.some(item => !item.diseaseId || !item.relation)
    if (isRequest) {
      message.error('请录完本条与本人关系和关系人疾病后添加');
      return false;
    }
    const newData = {
        relationValue:'',
        relation:'',
        diseaseId: '',
        age: '',
        lapseToId: '',
      }
      data.push(newData)
    this.setState({
      // loading: true,
      data:[...data]
    })
    console.log(this.state.data)
    // data = data.filter(item => {
    //   return item.relation && item.diseaseId
    // })
    // updateDiseaseInfo.familyDiseases = data
    // updateDiseaseInfo.chronicDiseases = []
    // await api.updateDiseaseInfo(patientId, updateDiseaseInfo);
    // this.initColumns()
  }
  // 删除慢病
  deleteSlowSick = async (value, index) => {
    const self = this
    const { patientId } = this.props;
    let { data } = this.state;
    const deleteData = {
      chronicDiseases: [],
      familyDiseases: [value]
    };
    confirm({
      title: '确认要删除么?',
      async onOk() {
        try {
          let newData = [...data];
          console.log(data,data.length)
          if (data.length === 1) {
            newData = [{
              relationValue: '',
              relation: '',
              diseaseId: '',
              age: '',
              lapseToId: '',
            }]
          } else {
            newData.splice(index, 1);
          }
          self.setState({
            data: [...newData]
          })
          // self.initColumns()
        } catch (e) {
          message.error(`删除失败 ${e.message}`);
        }
      },
      onCancel() {}
    });
  }
  // 选择关系
  relationChange = (val, index) => {
    const { data } = this.state;
    let newData = data;
    newData[index].relationValue = val
    newData[index].relation = val
    const initD = JSON.parse(JSON.stringify(newData))
    this.setState({
      data: initD
    })
  }
  // 转归选择
  lapseToIdChange = (val, index) => {
    const { data } = this.state;
    let newData = data;
    newData[index].lapseToId = val
    const initD = JSON.parse(JSON.stringify(newData))
    this.setState({
      data:initD
    })
  }
  // 年龄
  ageChange =(val, index) => {
    const { data } = this.state;
    let newData = data;
    newData[index].age = val
    this.setState({
      data:[...newData]
    })
  }
  // 鼠标离开年龄范围取值
  ageChangeSend= (val, index) => {
    const { data } = this.state;
    let newData = data;
    let age = val.target.value < 18 ? 18 : val.target.value>120?120:val.target.value ;
    newData[index].age = age;
    this.setState({
      data:newData
    })
  }
  render() {
    return (
      <div>
        <Table loading={ this.state.loading } className="sickTable" columns={this.state.columns} dataSource={this.state.data} pagination={ false } rowKey='key'/>
      </div>
    );
  }
}
